package DataFile;

import java.nio.ByteBuffer;
import java.util.LinkedList;

import ClassData.ExceptionHandler;

/**
 * Table for Exception Handlers.
 * @author Roman Richter, Dominik Ollesz
 * @date 05.05.2011
 */
public class Structure_ExceptionHandlerTable extends Structure_Template {

	LinkedList<Structure_ExceptionHandler> exceptionHandlerTable = 
		new LinkedList<Structure_ExceptionHandler>();

	
	public Structure_ExceptionHandlerTable() {
		// do nothing
	}

	public Structure_ExceptionHandlerTable(ExceptionHandler[] handlers) {
		if (handlers != null) {
			for(ExceptionHandler currentExceptionHandler : handlers) {
				exceptionHandlerTable.add(new Structure_ExceptionHandler(currentExceptionHandler));
			}
		}
	}
	
	public void addExceptionHandlers(ExceptionHandler[] handlers) {
		if (handlers != null) {
			for(ExceptionHandler currentExceptionHandler : handlers) {
				exceptionHandlerTable.add(new Structure_ExceptionHandler(currentExceptionHandler));
			}
		}
	}
	
	/**
	 * @return Elements inside ExceptionHandlerTable.
	 */
	public int size() {
		return(exceptionHandlerTable.size());	
	}
	
	/**
	 * Set a new base address (4 Bit aligned).
	 */
	protected int setBaseAddress(int newBaseAdress) {
		while ((newBaseAdress%4)!=0) {
			newBaseAdress++;
		}
		baseAdress=newBaseAdress;
		
		int handlerAddress = baseAdress;
		for (Structure_ExceptionHandler exceptionHandler : exceptionHandlerTable) {
			handlerAddress = exceptionHandler.setBaseAddress(handlerAddress);
		}
		
		return(handlerAddress);
	}
	
	protected int getMemorySize() {
		int mySize;
		mySize =(exceptionHandlerTable.size()*ADRESS_WIDTH*2);
		return(mySize);
	}
	
	protected int getTableDataMemorySize() {
		int mySize=0;
		for (Structure_ExceptionHandler handler : exceptionHandlerTable) {
			mySize+=handler.getMemorySize();
		}
		return(mySize);
	}
	
	protected String getMemoryMapAsString() {
		String returnString;
	
		returnString="\nException Handler Table : Base Adress - ";
		returnString+=getAdressAsHexString(baseAdress);
		returnString+=" : size - "+getMemorySize();
		returnString+="\n";
	
		return(returnString);
	}
	
	public Structure_ExceptionHandler get(int index) {
		return(exceptionHandlerTable.get(index));
	}
	
	@Override
	public void writeData(ByteBuffer fileData) {
		fileData.position(baseAdress-DataFileCreator.BASE_MEMORY_ADRESS);
		// write content of exception handler table
		for (Structure_ExceptionHandler exceptionHandler : exceptionHandlerTable) {
			exceptionHandler.writeData(fileData);
		}	
	}
	
}
